package grape.file.service.cloudstorage.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import grape.common.tools.IoStreamTool;
import grape.common.tools.PathTool;
import grape.file.service.cloudstorage.config.AliyunStorageConfig;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * @Auther: wzn
 * @Date: 2019/2/20 15:25
 * @Description: 阿里云存储
 */
@Service
public class AliyunCloudStorageServiceImpl extends AbstractCloudStorageService implements InitializingBean {

    private OSSClient client;
    @Autowired
    private AliyunStorageConfig config;

    @Override
    public void afterPropertiesSet() throws Exception {

        // 如果没有配置不初始化，保证应用能正常启动
        if (config.getAccessKeyId() == null) {
            return;
        }
        client = new OSSClient(config.getEndPoint(), config.getAccessKeyId(),
                config.getAccessKeySecret());

    }

    @Override
    public boolean support(String type) {
        return isEqual(config.uploadType(),type);
    }

    @Override
    public String upload(byte[] data, String filepath) {
        return upload(new ByteArrayInputStream(data), PathTool.concat(config.getPrefix() , filepath));
    }

    @Override
    public String uploadSuffix(byte[] data,String prefixPath, String suffix) {
        return upload(data, newPath(PathTool.concat(config.getPrefix() , prefixPath), suffix));
    }

    @Override
    public String upload(InputStream inputStream, String filepath) {
        try {
            client.putObject(config.getBucketName(), PathTool.concat(config.getPrefix() , filepath), inputStream);
        } catch (Exception e) {
            throw new RuntimeException("阿里去上传文件失败，请检查配置信息,"+e.getMessage(),e);
        }

        return getResult(config.getDomain() ,config.getPrefix() , filepath);
    }

    @Override
    public String uploadSuffix(InputStream inputStream,String prefixPath, String suffix) {
        return upload(inputStream, newPath(PathTool.concat( prefixPath), suffix));
    }

    @Override
    public byte[] download(String objectName) throws Throwable {
        objectName = PathTool.ensureNotBeginSlash(objectName);
        OSSObject object = client.getObject(config.getBucketName(), objectName);
        if (object != null) {
            return IoStreamTool.inputStreamToByteArray(object.getObjectContent());
        }
        return null;
    }

    @Override
    public int delete(String objectName) {
        client.deleteObject(new GenericRequest(config.getBucketName(),objectName));
        return 1;
    }

}
